#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/11/19 12:05
# @Author : 闫峰
# @File    : mongodb_utils.py
import json
from typing import Union
from datetime import datetime
import pymongo
from dateutil import parser


class MongoDBLink:

    # def __init__(self, host,port,username,password,dbname,coll_name):
    #     """
    #
    #     :param host:  Ip
    #     :param port:   端口
    #     :param username:  用户名
    #     :param password:  密码
    #     :param dbname:    数据库名
    #     :param coll_name:  集合名称
    #     """
    #     # 连接mongodb
    #
    #     self.host = host
    #     self.port = port
    #     self.username = username
    #     self.password = password
    #     self.dbname = dbname
    #     self.coll_name = coll_name
    #     # url = "mongodb://{}:{}@{}:{}/?authSource={}".format(self.username,self.password,self.host,self.port,self.dbname)
    #     uri = "mongodb://{}:{}@{}:{}/{}".format(self.username, self.password, self.host, self.port,self.username)
    #     self.client = pymongo.MongoClient(uri)
    #     self.db = self.client[self.dbname]
    #     self.collection  =self.db[self.coll_name]
    #
    #
    #
    # def select(self,sql):
    #     """
    #     查询
    #     :param sql:   mongodb查询语句
    #     :return:
    #     """
    #     res = self.collection.find_one(sql)
    #     return res
    #
    #
    # def select_many(self,sql,field):
    #
    #     result = []
    #     for i in self.collection.find(sql,field):
    #         result.append(i)
    #     return result

    def __init__(self, uri, dbname, coll_name):

        self.dbname = dbname
        self.coll_name = coll_name
        self.uri = uri
        self.client = pymongo.MongoClient(uri)
        self.db = self.client[self.dbname]
        self.collection = self.db[self.coll_name]

    # def select(self,sql,field):
    #     """
    #     查询
    #     :param sql:   mongodb查询语句
    #     :return:
    #     """
    #     res = self.collection.find(sql,field)
    #     res_dict = []
    #     for one in res:
    #         res_dict.append(one)
    #     return res_dict

    def select(self, sql):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        res = self.collection.find(sql)
        res_dict = []
        for one in res:
            res_dict.append(one)
        return res_dict

    def filter_projection_sort_limit(self, filter, projection, sort, limit=1000):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        res = self.collection.find(filter, projection).sort(sort).limit(limit)
        res_dict = []
        for one in res:
            one = self.verify(one)
            res_dict.append(one)
        self.client.close()
        return res_dict

    def select_skip_limit(self, sql, skip, limit):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        res = self.collection.find(sql).skip(skip).limit(limit)
        res_dict = []
        for one in res:
            one = self.verify(one)
            res_dict.append(one)
        return res_dict

    def select2(self, sql, field):
        """
        查询
        :param sql:   mongodb查询语句
        :return:
        """
        res = self.collection.find(sql, field).skip(0).limit(10)
        res_dict = []
        for one in res:
            res_dict.append(one)

        return res_dict

    def aggregate(self, pipeline):
        res_dict = []
        ii = self.collection.aggregate(pipeline)
        for i in ii:
            res_dict.append(i)
        return res_dict

    def verify(self, result: dict) -> Union[dict, None]:
        """验证结果能否被json.dumps序列化"""
        # 尝试变成字符串，解决datetime 无法被json 序列化问题
        try:
            json.dumps(result)
        except TypeError:  # TypeError: Object of type datetime is not JSON serializable
            for k, v in result.items():
                if isinstance(v, datetime):
                    result[k] = str(v)
        return result

if __name__ == '__main__':
    mongodb = MongoDBLink("mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin","test_zhcxkj_java_center","t_allegro_listing_template_detail_17")
    mongodb.filter_projection_sort_limit({"listingTemplateId":17},{},[("_id",1)])
    # mongodb.select({"listingTemplateId":17})

